package com.ywjh.inter.servlet.doc;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ywjh.inter.common.SystemConfig;
import com.ywjh.inter.entity.DocProfileEntity;
import com.ywjh.inter.entity.InstitutionEntity;
import com.ywjh.inter.service.InstService;
import com.ywjh.inter.service.UsersService;
import com.ywjh.inter.utils.StrUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class ListDoc extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -9093935007158053036L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html; charset=utf-8");

		JSONObject postData = StrUtil.getPostJSON(req);
		String act = postData.getString("act");
		JSONObject data = postData.getJSONObject("data");
		int r = 0;
		String e = "";
		JSONObject json = new JSONObject();
		switch (act) {
		case "list":
			int docId = data.getInt("doc_id");
			DocProfileEntity docProfileEntity = UsersService.getInstance().findDocProfileByUserId(docId);
			if (docProfileEntity != null) {
				List<DocProfileEntity> list = UsersService.getInstance().listManagedDocList(docProfileEntity.getInst_id(),
							docProfileEntity.getRule_level());
				JSONArray array = new JSONArray();
				for (DocProfileEntity entity : list) {
					if (entity.getUser_id() != docId) {
						JSONObject profile = entity.toJson();
						InstitutionEntity keshi = InstService.getInstance().findById(docProfileEntity.getInst_id());
						if (keshi != null) {
							profile.put("keshi", keshi.getName());
							InstitutionEntity bumen = InstService.getInstance().findById(keshi.getPid());
							if (bumen != null) {
								profile.put("bumen", bumen.getName());
								InstitutionEntity yiyuan = InstService.getInstance().findById(bumen.getPid());
								profile.put("yiyuan", yiyuan.getName());
							}
						}
						profile.put("head_url", SystemConfig.SERVER_DOMAIN
								+ UsersService.getInstance().findUserById(docId).getHead_url());
						array.add(profile);
					}
				}
				r = 1;
				json.put("d", array);
			} else {
				e = "没有找到医生信息";
			}

			break;
		}
		json.put("r", r);
		json.put("e", e);
		PrintWriter pw = resp.getWriter();
		pw.write(json.toString());
		pw.flush();
		pw.close();
	}

}
